package cn.ygh.bbo.framerwork.web;

import cn.ygh.bbo.common.exception.LoginException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;


/**
 * @author ygh
 * @Desc jwt token令牌工具
 * @date 2019/9/30
 */
public class TokenService {

    /**
     * 认证线程缓存
     */
    private ThreadLocal<String>threadLocal=new ThreadLocal<>();

    /**
     * key
     */
    private String secret = "geiangasfdjsikolk2123sd222fi221313jikolkijswe";

    /**
     * 单位毫秒 默认7天
     */
    private Integer time=60*1000*60*24*7;

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public Integer getTime() {
        return time;
    }

    public void setTime(Integer time) {
        this.time = time;
    }

    /**
     *  生成一个token
     */
    public String creatToken(String id) {
        return Jwts.builder()
                .setId(id)
                .setExpiration(new Date(System.currentTimeMillis()+time))
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    /**
     * 从token中解析出用户
     * @param token
     */
    public String parseToken(String token) throws LoginException {
        if (threadLocal.get()!=null){
            return threadLocal.get();
        }
        if (StringUtils.isBlank(token)){
            throw new LoginException("请先登陆");
        }
        Claims body = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token).getBody();
        String id=body.getId();
        if (StringUtils.isBlank(id)){
            throw new LoginException("请先登陆");
        }
        threadLocal.set(id);
        return id;
    }

    /**
     * 添加缓存
     * @return
     */
    public void bind(String id) {
        threadLocal.set(id);
    }

    /**
     * 清除缓存
     * @return
     */
    public void unbind() {
       threadLocal.remove();
    }

    /**
     * 获得当前用户
     * @return
     */
    public String get()  {
        return threadLocal.get();
    }

}
